package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    WeChatProperties weChatProperties;

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        // 1.使用HTTPClient
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("appid", weChatProperties.getAppid());
        paramsMap.put("secret", weChatProperties.getSecret());
        paramsMap.put("js_code", userLoginDTO.getCode());
        paramsMap.put("grant_type", "authorization_code");
        String loginResult = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramsMap);
        //2.解析loginResult
        String openid = JSONObject.parseObject(loginResult).getString("openid");
        // 3.判断openid 是否为null
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //4.判断是否为新用户
        User user = userMapper.selectByOpenId(openid);
        if (user == null) {
            user = User.builder().
                    openid(openid).
                    createTime(LocalDateTime.now()).
                    build();
            userMapper.insertUser(user);
        }
        // 5.不是返回 user
        return user;
    }
}
